package com.ittx.dzt.meituan.service;

import cn.hutool.core.collection.CollectionUtil;
import com.ittx.dzt.edi.constant.PlatformApiConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.meituan.constant.MeituanApiConstant;
import com.ittx.dzt.meituan.handler.AbstractMeituanByTimeApiHandler;
import com.ittx.dzt.sys.response.Result;
import lombok.extern.slf4j.Slf4j;
import open.dto.TimeFrameDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 商品信息全量下载
 * <p>
 * cy.sku.download.byTimeFrame
 * /api/v1/gw/goods/list (查询门店商品列表)  https://tscc.meituan.com/home/doc/bulkPurchasing/544
 * </p>
 *
 * @author wushixiong
 * @since 2022/5/6 16:55
 */
@Slf4j
@Service
public class MeituanAllSkuDownloadService extends AbstractMeituanByTimeApiHandler<TimeFrameDto> {

    private static final Integer DEFAULT_PAGE_SIZE = 20;
    @Autowired
    private MeituanSkuDownloadBySpuIdService meituanSkuDownloadBySpuIdService;


    @Override
    protected String getMqTopic() {
        return MeituanApiConstant.Rocket.MEITUAN_PRODUCT_LIST_BY_TIME_BATCH_SPLIT_TOPIC;
    }

    @Override
    public String getMeituanMethod() {
        return MeituanApiConstant.GOODS_LIST;
    }

    @Override
    public String getHttpMethod() {
        return MeituanApiConstant.ApiHttpMethod.POST;
    }

    @Override
    public String getLocalApiMethod() {
        return open.constant.PlatformApiConstant.InboundInterface.SKU_DOWNLOAD_BY_TIMEFRAME;
    }

    @Override
    protected Result<?> doProcessByNormalType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDto timeFrameDTO) {
        // 分发数据,异步下载
        Map<String, Boolean> logMap = new HashMap<>();
        return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, logMap);
    }

    @Override
    protected Result<?> doProcessByCheckType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDto timeFrameDTO) {
        //探查成功时不返回完整数据,只返回数量
        return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, null);
    }

    @Override
    protected Result<?> doProcessByIdType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDto timeFrameDTO) {
        String productId = platformApiParamDTO.getPlatformIdentifierTag();
        return this.asyncHandlerById(platformApiParamDTO, productId);
    }


    /**
     * 请求平台接口
     */
    private Result<?> requestListBySdk(PlatformApiParamDTO platformApiParamDTO, TimeFrameDto timeFrameDTO, Map<String, Boolean> logMap) {
        Map<String, String> params = new HashMap<>();
        params.put("poi_id", getPoIId(platformApiParamDTO));
        params.put("page_size", DEFAULT_PAGE_SIZE.toString());
        Long page = 1L;
        // 第一次查询，获取总页数 第一页为1
        params.put("page_index", page.toString());
        Result<?> result = this.executeMeituanApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
        if (!result.isSuccess()) {
            return result;
        }
        Map<String, Object> resultMap = (Map<String, Object>) result.getData();
        Map<String, Object> dataMap = (Map<String, Object>) resultMap.get(DATA_FIELD);
        // 商品总数
        int total = Integer.parseInt(dataMap.get("total").toString());
        // 探查模式只返回商品总数
        if (PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
            return Result.success().addData(total);
        }
        // 总页数
        Integer totalPage = this.totalPage(total, DEFAULT_PAGE_SIZE);
        if (totalPage > 0) {
            // 倒序查询，防止数据遗漏
            for (Integer i = totalPage; i > 0; i--) {
                params.put("page_index", i.toString());
                result = this.executeMeituanApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
                if (!result.isSuccess()) {
                    return result;
                }
                resultMap = (Map<String, Object>) result.getData();
                dataMap = (Map<String, Object>) resultMap.get(DATA_FIELD);
                List<Map<String, Object>> items = (List<Map<String, Object>>) dataMap.get("goods_list");
                if (CollectionUtil.isNotEmpty(items)) {
                    // 分发数据到MQ，异步消费下载
                    for (Map<String, Object> item : items) {
                        String productId = item.get("goods_id") + "";
                        sendToSplitTopic(platformApiParamDTO, productId, logMap);
                    }
                }
            }
        }
        return Result.success(logMap);
    }

    /**
     * 多线程处理逻辑
     */
    @Override
    public Result<?> asyncHandlerById(PlatformApiParamDTO platformApiParamDTO, String productId) {
        Result<?> result = meituanSkuDownloadBySpuIdService.getProductById(productId, platformApiParamDTO);
        if (result.hasError()) {
            return result;
        }
        return this.sendRequestToPlatform(platformApiParamDTO, result.getData(), true);
    }
}
